package cn.gjxblog.mq.pattern.topic;

import cn.gjxblog.mq.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/7/4 11:48
 */
public class Consumer {
    public static void main(String[] args) throws Exception {

        //1 创建连接
        Connection connection = ConnectionUtils.getConnection();

        //2 通过connection创建channel
        Channel channel = connection.createChannel();

        //3 声明一个类型为topic的exchange，并和一个队列建立绑定
        String exchangeName = "test_topic_exchange";
        String routingKey = "topic.#";
        String queueName = "test_topic_queue";
        channel.exchangeDeclare(exchangeName,"topic",true);
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueBind(queueName,exchangeName,routingKey);


        //4 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        //5 设置chanel
        channel.basicConsume(queueName,true,queueingConsumer);

        //6 获取消息
        while (true) {
            QueueingConsumer.Delivery deliver = queueingConsumer.nextDelivery();
            String msg = new String(deliver.getBody());
            System.out.println("msg is:" + msg);
        }

    }
}
